//
//  RegisterNickNamePortraitVC.m
//  Snigger
//
//  Created by Young on 16/8/22.
//  Copyright © 2016年 Smile. All rights reserved.
//

#import "RegisterNickNamePortraitVC.h"

#import <AssetsLibrary/AssetsLibrary.h>
#import <AssetsLibrary/ALAsset.h>
#import <AssetsLibrary/ALAssetsLibrary.h>
#import <AssetsLibrary/ALAssetsGroup.h>
#import <AssetsLibrary/ALAssetRepresentation.h>
#import "Switch.h"
#import "RegisterThirdViewController.h"
#import "EMClient.h"
#import "LoginViewController.h"
#import "Alertor.h"

#define kBackgroundColor [UIColor colorWithRed:236 / 256.0 green:237 / 256.0 blue:240 / 256.0 alpha:1.0]

@interface RegisterNickNamePortraitVC () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UIButton *portraitButton;
@property (weak, nonatomic) IBOutlet UITextField *nickNameTextField;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (copy, nonatomic) NSString *gender;
@property (strong, nonatomic) Switch *switcher;

@end

@implementation RegisterNickNamePortraitVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"Set portrait and nickname";
    self.view.backgroundColor = kBackgroundColor;
    _gender = @"男";
    _portraitButton.layer.cornerRadius = _portraitButton.bounds.size.width / 2.0;
    _portraitButton.layer.masksToBounds = YES;
    [_portraitButton addTarget:self action:@selector(tapPortraitAction:) forControlEvents:(UIControlEventTouchUpInside)];
    // 初始化Switcher
    [self initSwitcher];
    // 初始化注册按钮
    [self initRegisterButton];
}

- (void)initSwitcher {
    self.switcher = [[Switch alloc] initWithStringsArray:@[@"男", @"女"]];
    self.switcher.backgroundColor = [UIColor lightGrayColor];
    self.switcher.frame = CGRectMake(26, CGRectGetMaxY(self.nickNameTextField.frame) + 26, [UIScreen mainScreen].bounds.size.width - 52, 40);
    [self.scrollView addSubview:self.switcher];
    [self.switcher setPressedHandler:^(NSUInteger index) {
        if (index == 0) {
            _gender = @"男";
        } else {
            _gender = @"女";
        }
    }];
}

- (void)initRegisterButton {
    UIButton *registerButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    registerButton.frame = CGRectMake(26, CGRectGetMaxY(self.switcher.frame) + 26, [UIScreen mainScreen].bounds.size.width - 52, 50);
    [registerButton setTitle:@"Register" forState:(UIControlStateNormal)];
    [registerButton addTarget:self action:@selector(registerClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    registerButton.backgroundColor = [UIColor lightGrayColor];
    registerButton.layer.cornerRadius = 5;
    [self.scrollView addSubview:registerButton];
}

#pragma mark - 注册方法
- (void)registerClicked:(UIButton *)button {
    [[EMClient sharedClient] asyncRegisterWithUsername:_nickNameTextField.text password:_passwordString success:^{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"注册成功" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *successAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            LoginViewController *loginVC = [[LoginViewController alloc] init];
            
            [self.navigationController pushViewController:loginVC animated:YES];
        }];
        [alertController addAction:successAction];
        [self presentViewController:alertController animated:YES completion:nil];
    } failure:^(EMError *aError) {
        [self presentViewController:[[Alertor sharedAlertor] alertWithTitle:@"登录失败" message:[aError errorDescription] actionTitle:@"确定"] animated:YES completion:nil];
    }];
}

#pragma mark - 轻拍手势方法
- (void)tapPortraitAction:(UITapGestureRecognizer *)tap {
    // 获取系统相册
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"SelectPicture" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *action_Camera = [UIAlertAction actionWithTitle:@"FromCamera" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.editing = YES;
            picker.allowsEditing = YES;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:picker animated:YES completion:nil];
        } else {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Camera failed to be obtained." message:nil preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"Cancel" style:(UIAlertActionStyleCancel) handler:nil];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
    
    UIAlertAction *action_PhotoLibrary = [UIAlertAction actionWithTitle:@"FromPhotoLibrary" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            UIImagePickerController  *picker =[[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.editing = YES;
            picker.allowsEditing = YES;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:picker animated:YES completion:nil];
        } else {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"PhotoLibrary failed to be obtained." message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
    UIAlertAction *action_Cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action_Camera];
    [alert addAction:action_PhotoLibrary];
    [alert addAction:action_Cancel];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    /**
     *  相机代理
     */
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        // 获取裁剪图片
        UIImage *cameraImage = [info objectForKey:UIImagePickerControllerEditedImage];
        // 如果实拍的照,需要保存到本地
        UIImageWriteToSavedPhotosAlbum(cameraImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }
    /**
     *  相册代理
     */
    else if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        // 获取裁剪的图片
        UIImage *photoLibraryImage = [info objectForKey:UIImagePickerControllerEditedImage];
        [_portraitButton setBackgroundImage:photoLibraryImage forState:(UIControlStateNormal)];

        // 将图片转化成数据类型
        //        NSData *data = UIImageJPEGRepresentation(photoLibraryImage, 0.00001);
        //        AVFile *file = [AVFile fileWithName:@"userimage.png" data:data];
        //        [file saveInBackground];
        //        //
        //        AVQuery *query = [AVQuery queryWithClassName:@"_User"];
        //        [query whereKey:@"username" equalTo:[AVUser currentUser].username];
        //        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        //            if (!error) {
        //                // 检索成功
        //                AVObject *post = [AVObject objectWithoutDataWithClassName:@"_User" objectId:[[objects lastObject]objectId]];
        //                [post setObject:file forKey:@"pictrue"];
        //                [post saveInBackground];
        //            }else {
        //                NSLog(@"%@,%@",error,[error userInfo]);
        //            }
        //
        //        }];
    }
    //    [self.tableView reloadData];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//保存照片成功后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo{
    //    NSString *msg = nil ;
    //    if(error != NULL){
    //        msg = @"保存图片失败" ;
    //    }else{
    //        msg = @"保存图片成功" ;
    //        self.userHeadImage.image = image;
    //        NSData *data = UIImageJPEGRepresentation(image, 0.00001);
    //        AVFile *file = [AVFile fileWithName:@"userimage.png" data:data];
    //        [file saveInBackground];
    //        [self.tableView reloadData];
    //        //更新属性
    //        AVQuery *query = [AVQuery queryWithClassName:@"_User"];
    //        [query whereKey:@"username" equalTo:[AVUser currentUser].username];
    //        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    //            if (!error) {
    //                // 检索成功
    //                AVObject *post = [AVObject objectWithoutDataWithClassName:@"_User" objectId:[[objects lastObject]objectId]];
    //                [post setObject:file forKey:@"pictrue"];
    //                [post saveInBackground];
    //                [self.tableView reloadData];
    //            } else {
    //                // 输出错误信息
    //                NSLog(@"Error: %@ %@", error, [error userInfo]);
    //            }
    //        }];
    //
    //    }
    //    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存图片结果提示"
    //                                                    message:msg
    //                                                   delegate:self
    //                                          cancelButtonTitle:@"确定"
    //                                          otherButtonTitles:nil];
    //    
    //    [alert show];
    //    
}

#pragma mark - 对图片尺寸进行压缩
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}

#pragma mark - UIImagePickerController代理方法, 完成调用系统相册后执行

- (IBAction)tapScrollViewAction:(id)sender {
    [_nickNameTextField resignFirstResponder];
}

- (IBAction)tapBackgroundView:(id)sender {
    [_nickNameTextField resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
